﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;


/// <summary>
/// MD5加密
/// </summary>
public class MD5Encrypt
{
    /// <summary>
    /// 16位MD5加密
    /// </summary>
    /// <param name="password"></param>
    /// <param name="lowerCase"></param>
    /// <returns></returns>
    public static string Encrypt16(string input, bool lowerCase = true)
    {
        using (MD5 md5 = MD5.Create())
        {
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(input)), 4, 8);
            t2 = t2.Replace("-", "");
            if (lowerCase) return t2.ToLower();
            return t2;
        }
    }

    public static string Encrypt32(string str, bool lowerCase = true)
    {
        using (MD5 md5 = MD5.Create())
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            byte[] md5Buffer = md5.ComputeHash(buffer);
            string newstr = "";
            for (int i = 0; i < md5Buffer.Length; i++)
            {
                newstr += md5Buffer[i].ToString("x2");
            }
            if (lowerCase) return newstr.ToLower();
            return newstr.ToUpper();
        }
    }




    /// <summary>
    /// 64位MD5加密
    /// </summary>
    /// <param name="password"></param>
    /// <returns></returns>
    public static string Encrypt64(string password)
    {
        if (password.IsNull())
            return "";

        using var md5 = MD5.Create();
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
        return Convert.ToBase64String(s);
    }

    public static string GetHash(Stream stream)
    {
        StringBuilder sb = new();
        using var md5 = MD5.Create();
        byte[] hashBytes = md5.ComputeHash(stream);
        foreach (byte bt in hashBytes)
        {
            sb.Append(bt.ToString("x2"));
        }

        return sb.ToString();
    }
}